<template>
  <div class="app-container customer-div">
    <el-menu :default-active="listQuery.tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="my">我的</el-menu-item>
      <el-menu-item index="department" v-if="departmentOrderSaleProfitAnalysis">部门</el-menu-item>
      <el-menu-item index="all" v-if="allOrderSaleProfitAnalysis">全部</el-menu-item>
    </el-menu>
    <div style="margin-top: 20px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="130px">
        <el-form-item label="订单编号：">
          <el-input v-model="listQuery.orderSn" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户名称：">
          <el-select
            clearable
            v-model="listQuery.customerId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="loading">
            <el-option
              v-for="item in customerList"
              :key="item.customerId"
              :label="item.customerName"
              :value="item.customerId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售员：">
          <el-select v-model="listQuery.userIds" placeholder="请选择" clearable filterable>
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品名：">
          <el-select v-model="listQuery.goodsClass" @change="changeGoodsName" clearable filterable>
            <el-option v-for="item in goodsClassList" :value="item" :label="item" :key="item"></el-option>
          </el-select>
<!--          <el-input v-model="listQuery.goodsName"></el-input>-->
        </el-form-item>
        <el-form-item label="牌号：">
          <el-select v-model="listQuery.kingGoodsId" filterable placeholder="请选择" clearable>
            <el-option
                    v-for="item in goodsList"
                    :key="item.kingId"
                    :label="item.goodsSn"
                    :value="item.kingId">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="订单日期：">
          <el-date-picker
            v-model="listQuery.date"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="发货状态：">
          <el-select v-model.number="listQuery.shipState" class="input-width" style="width:195px" placeholder="请选择" clearable>
            <el-option :value="0" label="未发货" :key="0"></el-option>
            <el-option :value="1" label="部分发货" :key="1"></el-option>
            <el-option :value="2" label="已发货" :key="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
                  @click="handleSearchList()"
                  type="primary">
            查询
          </el-button>
          <el-button
            v-if="listQuery.tab == 'all' && allOrderSaleProfitAnalysisExport"
            :loading="btnloading"
            @click="downloadExcel"
            type="primary">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div style="margin:20px 0;font-size:14px;">
      <span>销售数量<b style="padding:0 5px">{{ statistics.goodsNum }}</b>吨，预估订单毛利<b style="padding:0 5px">{{ statistics.goodsNumProfit }}</b>元，
        未出库数量<b style="padding:0 5px" >{{ statistics.goodsUnShipNum }}</b>吨，预估未出库毛利<b style="padding:0 5px">{{statistics.goodsUnShipProfit}}</b>元，已出库数量<b style="padding:0 5px">{{statistics.goodsShipNum}}</b>吨，
        销售出库毛利<b style="padding:0 5px">{{statistics.goodsShipProfit}}</b>元</span>
    </div>

    <!--数据列表-->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="list"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column
                prop="orderSn"
                label="订单编码"
                align="center"
                width="150">
          <template slot-scope="scope">
              {{scope.row.orderSn}}
          </template>
        </el-table-column>
        <el-table-column
                label="客户名称"
                align="center"
                width="180">
          <template slot-scope="scope">
             {{scope.row.customerName}}
          </template>
        </el-table-column>
        <el-table-column
          prop="userName"
          label="销售员"
          width="120"
          align="center">
        </el-table-column>
        <el-table-column
          prop="goodsName"
          label="品类"
          width="180"
          align="center">
        </el-table-column>
        <el-table-column
          prop="goodsSn"
          label="牌号"
          width="180"
          align="center">
        </el-table-column>
        <el-table-column
          prop="goodsNum"
          label="订单数量"
          width="120"
          align="center">
        </el-table-column>

        <el-table-column
                class-name="cspantd"
                label="订单分类"
                align="center"
                width="180">
          <template slot-scope="scope">
             {{scope.row.orderCustomerType}}
          </template>
        </el-table-column>
        <el-table-column
          label="预估订单毛利"
          align="center"
          width="180">
          <template slot-scope="scope">
             {{scope.row.goodsNumProfit}}
          </template>
        </el-table-column>
        <el-table-column
                prop="goodsUnShipNum"
                label="未出库数量"
                align="center"
                width="150">
        </el-table-column>
        <el-table-column
                prop="goodsUnShipProfit"
                label="预估未出库毛利"
                align="center"
                width="180">
        </el-table-column>
        <el-table-column
          label="已出库数量"
          align="center"
          width="150">
          <template slot-scope="scope">
            {{scope.row.goodsShipNum}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="销售出库毛利"
          width="180">
          <template slot-scope="scope">
             {{scope.row.goodsShipProfit}}
          </template>
        </el-table-column>
        <el-table-column
          label="发货状态"
          align="center"
          width="100">
          <template slot-scope="scope">
              {{scope.row.shipState}}
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="count">
      </el-pagination>
    </div>

  </div>
</template>

<script>
    import {orderGoodsList,getCustomerOption,getOrderUsersList,getGoodsClass} from '@/api/partner'
    import { orderSaleProfitAnalysis } from '@/api/company';
    import {saleOrderReport} from '@/api/order'
    import {formatDate} from '@/utils/date';
    import store from '@/store'
    import { mapGetters } from 'vuex'
    const defaultListQuery={
      "tab" : "my", //我的-my,部门-department，全部-all
      "date" : [],  //下单时间
      "userIds" : "",  //业务员
      "goodsClass" : "", //品类
      "kingGoodsId" : "",   //指定牌号产品ID
      "orderSn" : "", //订单号
      "shipState" : "",//发货状态(0未发货，1部分发货，2已发货)
      customerId:'',
      "pageNum" : 1,
      "pageSize" : 10
    };
    export default {
        name: "saleReport",
        data(){
            return{
                roles:store.getters.roles ? store.getters.roles : [],
                listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
                list:[],
                count:0,
                loading:false,
                goodsList:[],
                customerList:[],
                userOptionList:[],
                divisionList:[],
              orderStateList:[],
              goodsClassList:[],
              statistics:{},
              btnloading:false
            }
        },
        computed: {
          ...mapGetters([
            'name',
            'mobile',
            'userId'
          ]),
          departmentOrderSaleProfitAnalysis() {
            if (this.roles.indexOf("departmentOrderSaleProfitAnalysis") != -1) {
              return true
            } else {
              return false
            }
          },
          allOrderSaleProfitAnalysis() {
            if (this.roles.indexOf("allOrderSaleProfitAnalysis") != -1) {
              return true
            } else {
              return false
            }
          },
          allOrderSaleProfitAnalysisExport(){
            if (this.roles.indexOf("allOrderSaleProfitAnalysisExport") != -1) {
              return true
            } else {
              return false
            }
          }

        },
        created() {
          let now = new Date();
          let nowMonth = now.getMonth(); //当前月
          let nowYear = now.getFullYear(); //当前年
          //本月的开始时间
          let monthStartDate = new Date(nowYear, nowMonth, 1);
          //本月的结束时间
          let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
          let startDate = formatDate(monthStartDate, 'yyyy-MM-dd');
          let endDate = formatDate(monthEndDate, 'yyyy-MM-dd');
          this.listQuery.date = [startDate,endDate];
          this.getListData();
          this.getUserOptionList()
          this.getGoodsClassList()
          this.getgoodsList()
        },
        filters: {
            formatTime(time) {
                let date = new Date(time);
                return formatDate(date, 'yyyy-MM-dd')
            },
        },
        methods:{
          //下载excle
          downloadExcel(){
            let params
            params = JSON.parse(JSON.stringify(this.listQuery));
            params.isExport = 1;
            delete params.pageSize;
            delete params.pageNum;
            this.btnloading = true
            orderSaleProfitAnalysis(params).then((res)=>{
              this.btnloading = false;
              require.ensure([], () => {
                const { export_json_to_excel } = require('sheet/Export2Excel');
                const tHeader = res.title;
                const filterVal = res.columns;
                const list = res.list;
                const data = this.formatJson(filterVal, list);
                export_json_to_excel(tHeader, data, res.fileName);
              })
            }).catch(()=>{
              this.btnloading = false;
            })
          },

          //下载表格数据格式化
          formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]))
          },
          changeGoodsName(){
            this.goodsList = [];
            this.listQuery.kingGoodsId = ''
            this.getgoodsList()
          },
          getGoodsClassList(){
            getGoodsClass().then((res)=>{
              this.goodsClassList = res
            })
          },
          getgoodsList(){
            orderGoodsList({goodsName:this.listQuery.goodsClass}).then((res)=>{
              this.goodsList = res.list
            })
          },


          /**
           * 切换选择状态
           */
          handleSelect(key, keyPath) {
            this.listQuery = JSON.parse(JSON.stringify(defaultListQuery))
            this.listQuery.tab = key;
            let now = new Date();
            let nowMonth = now.getMonth(); //当前月
            let nowYear = now.getFullYear(); //当前年
            //本月的开始时间
            let monthStartDate = new Date(nowYear, nowMonth, 1);
            //本月的结束时间
            let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
            let startDate = formatDate(monthStartDate, 'yyyy-MM-dd');
            let endDate = formatDate(monthEndDate, 'yyyy-MM-dd');
            this.listQuery.date = [startDate,endDate];
            this.handleSearchList();
          },



          //获取员工下拉选项
          getUserOptionList(){
            getOrderUsersList({status:1}).then((res)=>{
              this.userOptionList = res;
            })
          },
          //查询获取客户列表
          remoteMethod(query) {
            if(query && query!= ''){
              this.loading = true;
              getCustomerOption({keywords:query}).then(response => {
                this.customerList = response;
                this.loading = false;
              }).catch(()=>{
                this.loading = false;
              });
            }
          },
            handleSearchList(){
                this.listQuery.pageNum = 1;
                this.getListData();
            },

            handleSizeChange(val){
                this.listQuery.pageNum = 1;
                this.listQuery.pageSize = val;
                this.getListData();
            },
            handleCurrentChange(val){
                this.listQuery.pageNum = val;
                this.getListData();
            },

            getListData(){
              this.loading = true;
              orderSaleProfitAnalysis(this.listQuery).then((res)=>{
                this.list = res.list;
                this.count = res.count;
                this.statistics = res.statistics
                this.loading = false;
              }).catch(()=>{
                this.loading = false;
              })
            },

        },
    }
</script>



